<template>
  <div class="list" ref="wrapper">
    <!--这个div 放在这里是为了满足 better-scroll 对 DOM 的要求-->
    <div>
      <div class="area">
        <div class="title border-topbottom">当前城市</div>
        <div class="your-pos">
          <div class="button-wrapper">
            <div class="button">{{this.currentCity}}</div>
          </div>
        </div>
      </div>
      <div class="area">
        <div class="title border-topbottom">热门城市</div>
        <div class="your-pos">
          <div
            class="button-wrapper"
            v-for="item of hotCities"
            :key="item.id"
            @click="handleItemClick"
          >
            <div class="button">{{item.name}}</div>
          </div>
        </div>
      </div>
      <div
          class="area"
          v-for="(item, key) of cities"
          :key="key"
          :ref="key"
      >
        <div class="title border-topbottom">{{key}}</div>
        <ul class="item-list">
          <li
            class="item border-bottom"
            v-for="innerItem of item"
            :key="innerItem.id"
            @click="handleItemClick"
          >
            {{innerItem.name}}
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import BScroll from 'better-scroll'
import {mapState, mapMutations} from 'vuex'
export default {
  name: 'CityList',
  props: {
    hotCities: Array,
    cities: Object,
    letter: String
  },
  computed: {
    ...mapState({
      currentCity: 'city'
    })
  },
  methods: {
    handleItemClick (city) {
      // dispatch 调用 actions ，actions再去调用mutations
      // this.$store.dispatch('changeCity', city)
      // 通过 commit 直接调用 mutations 可以跳过actions
      // this.$store.commit('changeCity', city)
      this.changeCity(city)
      this.$router.push('/')
    },
    ...mapMutations(['changeCity'])
  },
  mounted () {
    this.scroll = new BScroll(this.$refs.wrapper)
  },
  watch: {
    letter () {
      if (this.letter) {
        const element = this.$refs[this.letter][0]
        this.scroll.scrollToElement(element)
      }
    }
  }
}
</script>

<style scoped lang="stylus">
  .border-topbottom
    &:before
      border-color #cccccc
    &:after
      border-color #cccccc
  .border-bottom
    &:before
      border-color #cccccc
  .list
    position absolute
    top 1.68rem
    left 0
    bottom 0
    right 0
    overflow hidden
    .title
      line-height .4rem
      background-color #eeeeee
      padding-left .2rem
      padding-top .1rem
      padding-bottom .1rem
    .your-pos
      padding .1rem .6rem .1rem .1rem
      overflow hidden
      .button-wrapper
        width 33.33333%
        float left
        .button
          padding .1rem
          text-align center
          margin .1rem
          border .02rem solid #cccccc
          border-radius .1rem
    .item-list
      .item
        line-height .74rem
        color #666666
        padding-left .2rem
</style>
